<template>
  <div class="app-container h-flex">
    <div class="tree-box app-container__left">
      <div class="type-title">部门</div>
      <el-tree
        ref="tree_box"
        :data="deptTreeData"
        node-key="id"
        icon-class="el-icon-arrow-right"
        :expand-on-click-node="false"
        default-expand-all
        :props="defaultDeptProps"
        @node-click="nodeClick" />
    </div>
    <div ref="tree_box_right" class="h-flex-elastic v-flex overflow-hidden app-container__right">
      <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm">
        <el-button
          v-permission-button="'ITPS-DELETE'"
          class="filter-form__button icon-red"
          size="mini"
          type="primary"
          icon="el-icon-delete"
          @click="deleteDatas">删除</el-button>
      </filter-form>
      <div ref="main" class="v-flex-elastic">
        <el-table
          v-if="height>0"
          ref="multipleTable"
          v-loading="listLoading"
          :data="tableData"
          border
          :height="height"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column align="center" type="selection" width="50" />
          <el-table-column prop="deptName" show-overflow-tooltip label="部门" />
          <el-table-column prop="staffName" show-overflow-tooltip label="职工姓名" />
          <el-table-column prop="username" show-overflow-tooltip label="登录名" />
          <el-table-column label="所属应用" show-overflow-tooltip align="center">
            <template slot-scope="{row}">
              <span
                v-for="(item,index) in row.appList"
                :key="item.id">{{ index>0?' / ':'' }}{{ item.appName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="角色" show-overflow-tooltip align="center">
            <template slot-scope="{row}">
              <span
                v-for="(item,index) in row.roleNameList"
                :key="item.id">{{ index>0?' / ':'' }}{{ item.roleName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="启用" align="center" width="70">
            <template slot-scope="{row,$index}">
              <el-switch v-model="row.status" @change="enable(row,$index)" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="210"
            class-name="small-padding fixed-width">
            <template slot-scope="{row ,$index}">
              <el-button
                v-permission-button="'ITPS-VIEW'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-view"
                @click="view(row)" />
              <el-button
                v-permission-button="'ITPS-UPDATE'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-edit"
                @click="updateForm(row,$index)" />
              <el-button
                v-permission-button="'ITPS-DELETE'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-delete"
                @click="deleteData(row,$index)" />
              <el-button v-permission-button="'ITPS-EXPORT'" size="mini" class="td-btn-operation" @click="resetPwd(row)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-box">
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :size.sync="listQuery.size"
          @pagination="getList" />
      </div>

      <base-dialog
        class="user-dialog"
        :visible.sync="dialog.visible"
        :title="dialog.title"
        :loading="dialog.loading"
        :disabled="dialog.disabled"
        @open="beforeOpenDialog"
        @updateData="updateData">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          :disabled="dialog.disabled"
          label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门" prop="deptId">
                <select-tree v-model="temp.deptId" :options="deptTreeData" :props="defaultProps" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职工姓名" prop="staffId">
                <el-select
                  v-model="temp.staffId"
                  filterable
                  clearable
                  :filter-method="filterStaff"
                  @visible-change="staffVisibleChange">
                  <el-option
                    v-for="item in staffData"
                    :key="item.id"
                    :label="(item.deptName?item.deptName+'-':'')+item.staffName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="登录名" prop="username">
                <el-input v-model="temp.username" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用">
                <el-switch v-model="temp.status" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="所属应用" prop="appIds">
                <el-select
                  v-model="temp.appIds"
                  multiple
                  class="filter-item"
                  style="width: 100%"
                  @change="chooseApp">
                  <el-option
                    v-for="item in appList"
                    :key="item.id"
                    :label="item.appName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="角色：">
                <el-table
                  v-if="height>0"
                  v-loading="listLoading"
                  :data="tableData1"
                  height="190"
                  border
                  row-key="id"
                  tooltip-effect="dark"
                  style="width: 100%">
                  <el-table-column label="平台应用" width="200">
                    <template slot-scope="{row}">{{ row.platformName }} > {{ row.appName }}</template>
                  </el-table-column>
                  <el-table-column label="权限" class-name="small-padding fixed-width">
                    <template slot-scope="{row,$index}">
                      <el-checkbox-group
                        v-if="row.roleList.length>0"
                        v-model="roleList[$index].actions">
                        <el-row :gutter="5">
                          <el-col
                            v-for="item in row.roleList"
                            :key="item.id"
                            style="overflow:hidden;"
                            :span="8"
                            :title="item.roleName">
                            <el-checkbox :label="item.id">{{ item.roleName }}</el-checkbox>
                          </el-col>
                        </el-row>
                      </el-checkbox-group>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </base-dialog>
      <!-- <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        width="900px">
        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="!disabled"
            type="primary"
            @click="dialogStatus==='create'?addData():updateData()">保存</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </el-dialog> -->
    </div>
  </div>
</template>

<script>
import { getListTree } from '@/api/dsc/system/department'
import { getListRole } from '@/api/dsc/system/role'
import {
  getList,
  resetPwd,
  getDefaultPwd,
  saveOrUpdate,
  deleteById,
  deleteByIds
} from '@/api/dsc/system/user'
import PinyinHelper from 'pinyin4js'
import { getListAll } from '@/api/dsc/system/worker'
import { getAppList } from '@/api/dsc/system/application'
import { Message } from 'element-ui'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscUser',
  mixins: [tableMixin],
  data() {
    return {
      appList: [],
      // 职工
      staffData: [],
      staffDataAll: [],
      // 部门树
      deptTreeData: [],
      defaultDeptProps: {
        children: 'children',
        label: 'label'
      },
      // 数据默认字段
      defaultProps: {
        parent: 'parentId', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'label', // 标签显示
        children: 'children' // 子级
      },
      treeHeight: 0, // tree高度
      height: 0, // table高度
      tableData1: [],
      tableData: [], // 表格数据
      roleList: [],
      listQuery: {
        // 搜索条件
        deptId: '',
        page: 1,
        size: 20,
        keyName: ''
      },
      filterData: {
        keyName: {
          key: 'keyName',
          type: 'input',
          placeholder: '请输入登录名、姓名'
        }
      },
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      defaultPwd: '', // 用户默认密码
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {
        // 弹窗表单
        id: null,
        deptId: '',
        staffId: '',
        username: '',
        appIds: [],
        status: true
      },
      rowIndex: null,
      rules: {},
      rulesModel: {
        deptId: [{ required: true, message: '必选', trigger: 'change' }],
        username: [
          { required: true, message: '必填', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '必填', trigger: 'blur' },
          { max: 255, message: '小于255个字符', trigger: 'blur' }
        ],
        appIds: {
          type: 'array',
          required: true,
          message: '请选择',
          trigger: 'change'
        }
      },
      listLoading: false,
      disabled: false, // 是否禁止表单操作
      multipleSelection: [] // 选择行的复选框
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    this.getListTree()
    this.getListRole()
    // 查询应用列表
    getAppList({}).then(response => {
      this.appList = response.data
    })
    // 调用默认密码
    getDefaultPwd({}).then(response => {
      this.defaultPwd = response.data
    })
    // 查询职工列表
    getListAll({}).then(response => {
      this.staffDataAll = response.data
      this.staffDataAll.forEach((e, i) => {
        e['pinyin'] = PinyinHelper.getShortPinyin(e.staffName)
      })
      this.staffData = Object.assign(this.staffDataAll)
    })
  },
  methods: {
    // 通过首字母查询职工
    filterStaff(val) {
      this.staffData = this.staffDataAll.filter((item) => {
        if (item.pinyin.includes(val) ||
            item.staffName.includes(val) ||
            (item.deptName && item.deptName.includes(val))) return true
      })
    },
    staffVisibleChange(val) {
      if (val) {
        this.staffData = this.staffDataAll.slice()
      }
    },
    // 选择应用
    chooseApp() {
      this.getListRole()
    },
    // 通过应用id查询所属角色
    getListRole() {
      if (!this.temp.appIds) {
        this.temp.appIds = []
      }
      return getListRole({ appIds: this.temp.appIds.join(',') }).then(
        response => {
          const roleList = this.roleList.reduce((result, item) => {
            return result.concat(item.actions)
          }, [])
          this.roleList = []
          this.tableData1 = response.data
          for (let j = 0, len = this.tableData1.length; j < len; j++) {
            this.tableData1[j].roleList = this.tableData1[j].roleList.filter(item => !item.delFlag)
            this.roleList.push({
              actions: roleList.filter(item => this.tableData1[j].roleList.some(child => child.id === item))
            })
          }
        }
      )
    },
    // 查询部门树
    getListTree() {
      getListTree({}).then(response => {
        this.deptTreeData = response.data
      })
      this.search()
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        for (const i of this.tableData) {
          i.status = !!i.status
        }
        setTimeout(() => {
          this.listLoading = false
        }, 0 * 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 点击tree节点回调
    nodeClick(data) {
      this.listQuery.deptId = data.id
      this.search()
    },
    // 搜索
    search() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      this.roleList.forEach(item => {
        item.actions = []
      })
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.rules = Object.assign({}, this.rulesModel)
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    async view(row) {
      // this.disabled = true
      this.temp = Object.assign({}, this.tempForm) // copy obj
      this.temp = Object.assign(this.temp, row) // copy obj
      await this.getListRole()
      this.initRoleList(this.temp.roles)
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    async updateForm(row, $index) {
      // this.disabled = false
      this.rowIndex = $index
      this.temp = Object.assign({}, this.tempForm) // copy obj
      this.temp = Object.assign(this.temp, row) // copy obj
      await this.getListRole()
      this.initRoleList(this.temp.roles)
      // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    initRoleList(roles) {
      this.tableData1.forEach((e, i) => {
        this.roleList[i].actions = []
        for (const j of e.roleList) {
          if (roles && roles.includes(j.id)) {
            this.roleList[i].actions.push(j.id)
          }
        }
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp, 2)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      this.listLoading = true
      const param = Object.assign({}, params)
      const roles = []
      for (const i of this.roleList) {
        for (const j of i.actions) {
          roles.push(j)
        }
      }
      param.roles = Object.assign([], roles)
      param.status = param.status ? 1 : 0
      saveOrUpdate(param)
        .then(response => {
          response.data.status = !!response.data.status
          if (this.dialog.title === '添加') {
            this.$alert(this.defaultPwd, '默认密码', {
              confirmButtonText: '确定'
            })
            this.tableData.unshift(response.data)
            this.total++
          } else {
            Object.assign(this.tableData[this.rowIndex], response.data)
          }
          this.notifiySuccess('保存成功!')
          this.dialog.visible = false
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?')
        .then(() => {
          deleteById(row.id).then(response => {
            this.notifiySuccess('删除成功!')
            this.tableData.splice($index, 1)
            this.total--
          })
        })
        .catch(() => {})
    },
    resetPwd(row) {
      this.confirmBox('确定重置密码?')
        .then(() => {
          resetPwd(row.id).then(response => {
            this.notifiySuccess('重置成功!')
          })
        })
        .catch(() => {})
    },
    // 启用、停用
    enable(row, $index) {
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    },
    // 批量删除
    deleteDatas() {
      let ids = ''
      for (const i of this.multipleSelection) {
        ids += ',' + i.id
      }
      ids = ids.substring(1)
      if (!ids) {
        Message({
          message: '请至少选择一条数据',
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      this.confirmBox('确定删除?')
        .then(() => {
          deleteByIds({ ids: ids }).then(response => {
            this.notifiySuccess('删除成功!')
            this.search()
          })
        })
        .catch(() => {})
    },
    // 选择行复选框
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 全选、反选
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>
<style lang="scss">
.el-dialog {
  .el-table__body-wrapper {
    overflow: hidden;
  }
}
</style>
